<template>
  <div class="app-container">
    <el-form size="small" label-width="80px" ref="orderForm" :rules="rules" :model="crud.order">

      <!-- :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'" -->
      <el-row :gutter="10">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="业务日期">
            <el-date-picker
             :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
              v-model="crud.order.busDate"
              type="date"
              style="width: 100%;"
              default-value
              format="yyyy - MM - dd "
              value-format="yyyy-MM-dd"
              placeholder="系统自动生成">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="单据编号">
            <el-input :disabled="true" v-model="crud.order.code" placeholder="请输入单据编号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="供应商" prop="supplierId">
            <zSelect :value.sync="crud.order.supplierId"
             :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                     :showName="crud.order.supplierName"
                     url="api/dropDown/basCustomerList"
                     :params="{ isContact: '1,2' }"
                     style="width:  100%" @change="changeSupplier"/>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="客户" prop="customerId">
            <zSelect :value.sync="crud.order.customerId"
             :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                     :showName="crud.order.customerName"
                     :label="crud.order.customerName" @change="changeCustomer"
                     url="api/dropDown/basCustomerList"
                     :params="{ isContact: '0,2' }"
                     style="width: 100%;" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="状态" prop="orderStatus">
            <el-select :disabled="true" v-model="crud.order.orderStatus" class="filter-item" clearable
                       placeholder="请选择状态" size="small"
                       style="width: 100%;">
              <el-option
                v-for="item in dict.common_order_status"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="所属部门" prop="deptId">
            <treeselect
              :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
              v-model="crud.order.deptId"
              :options="depts"
              placeholder="选择部门"
              :normalizer="normalizer"
              @change="changeDept"
            >
            </treeselect>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="经办人" prop="userId">
            <zSelect :value.sync="crud.order.userId"
             :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                     :showName="crud.order.userName"
                     :label="crud.order.userName" url="api/dropDown/sysUserList"
                     :params="userParams"
                     style="width:  100%"/>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="费用类型" prop="type">
            <el-select v-model="crud.order.type" class="filter-item" clearable placeholder="请选择费用类型" size="small"
             :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                       style="width: 100%;">
              <el-option
                v-for="item in dict.t_finance_daily_cost_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <!-- <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="银行" prop="bankId">
            <zSelect :value.sync="crud.order.bankId"
                     :showName="crud.order.bankName"
                     :label="crud.order.bankName"
                     url="api/dropDown/basBankList"
                     @change="changeBank"/>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="银行支行" prop="bankOpenBranch">
            <el-input v-model="crud.order.bankOpenBranch" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="银行账户" prop="bankAccount">
            <el-input v-model="crud.order.bankAccount" :disabled="true"></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="审核时间" prop="auditTime">
            <el-date-picker
              v-model="crud.order.auditTime"
              :disabled="true"
              type="date"
              style="width: 100%;"
              default-value
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="打印状态" prop="isPrint">
            <el-select v-model="crud.order.isPrint" :disabled="true" class="filter-item" clearable placeholder="状态"
                       size="small"
                       style="width: 100%;">
              <el-option v-for="item in dict.common_yes_or_no" :key="item.id" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="费用总额" prop="isPrint">
            <el-input
              type="number"
              min="0"
              :disabled="true"
              v-model="getTaxAmount"
              placeholder="请输入金额">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="14" :lg="12" :xl="12">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="text"
              v-model="crud.order.remark"
              placeholder="请输入备注">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <crudOperation :permission="permission">
       <el-button
        :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
        slot="left"
        class="filter-item"
        size="mini"
        type="primary"
        @click="addRow(0)"
      >
        新增
      </el-button>
      <el-button slot="left" class="filter-item" size="mini" type="warning"
                 :loading="crud.copyLoading" @click="copyOrder" v-permission="permission.add">
        复制
      </el-button>
      <el-button
        slot="left"
        class="filter-item"
        size="mini"
        type="primary"
        @click="submit"
      >
        保存
      </el-button>
      <el-button slot="right" class="filter-item" size="mini" type="success"
                 :disabled="crud.order.orderStatus !== 'SAVE'"
                 :loading="crud.passLoading" @click="crud.doDetailPassOrReject('PASS',id)">
        审核
      </el-button>
      <el-button slot="right" class="filter-item" size="mini" type="info" :loading="crud.rejectLoading"
                 :disabled="crud.order.orderStatus !== 'PASS'" @click="crud.doDetailPassOrReject('REJECT',id)">
        反审
      </el-button>
      <el-button
        slot="right"
        class="filter-item"
        size="mini"
        type="primary"
        @click="crud.toPrint()"
      >
        打印
      </el-button>
    </crudOperation>
    <!-- </crudOperation> -->
    <!--表格渲染-->

    <el-table ref="feeTable" stripe border v-loading="crud.loading" :row-class-name="crud.tableRowClassName"
              :data="crud.order.detailList"
              size="small" style="width: 100%;"
              sortable="custom"
              :show-summary="true"
              :summary-method="sumMoney"
              @selection-change="selectChange"
    >
      <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
      <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号"/>
      <el-table-column width="160" :render-header="crud.renderHeader" v-if="columns.visible('subjectCode')"
                       prop="subjectCode"
                       label="费用编号">
        <template slot-scope="{row}">
          <el-input :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'" v-model="row.subjectCode" placeholder="请输入费用编号"></el-input>
        </template>
      </el-table-column>
      <el-table-column width="160" :render-header="crud.renderHeader" v-if="columns.visible('subjectId')"
                       prop="subjectId"
                       label="费用名称">
        <template slot-scope="{row,$index}">
          <el-select-tree
            :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
            placeholder="请选择内容"
            :data="subjects"
            v-model="row.subjectId"
            :filterable="true"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            @node-click="changeSubjects($event,$index)"
          ></el-select-tree>
        </template>
      </el-table-column>
      <el-table-column :render-header="crud.renderHeader" v-if="false" prop="goodsBrandName" label="商品品牌 "/>
      <el-table-column width="160" :render-header="crud.renderHeader" v-if="columns.visible('goodsBrandId')"
                       prop="goodsBrandId"
                       label="商品品牌">
        <template slot-scope="{row}">
          <zSelect
            :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
            :value.sync="row.goodsBrandId == 0?null:row.goodsBrandId"
            :showName="row.goodsBrandName"
            placeholder="请选择品牌"
            url="api/dropDown/basGoodsBrandList"/>
        </template>
      </el-table-column>
      <el-table-column width="180" :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')"
                       prop="taxAmount"
                       label="金额">
        <template slot-scope="{row,$index}">
          <el-input-number
            style="width:100%"
            :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
            v-model="row.taxAmount"
            :precision="2"
            :step="0.1"
            :min="0"
            @change="changeMoney()"
          />
        </template>
      </el-table-column>
      <el-table-column width="400" :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark"
                       label="备注">
        <template  slot-scope="{row}">
          <el-input style="width: 400px"  v-model="row.remark" placeholder="请输入备注"></el-input>
        </template>
      </el-table-column>
      <el-table-column width="200" :render-header="crud.renderHeader" v-if="columns.visible('orderRemark')"
                       prop="orderRemark"
                       label="提要">
        <template slot-scope="{row}">
          <el-input :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'" v-model="row.orderRemark" placeholder="请输入提要"></el-input>
        </template>
      </el-table-column>
      <el-table-column :render-header="crud.renderHeader"
                       v-permission="['admin','financeDailyCost:edit','financeDailyCost:del']" label="操作"
                       align="center">
        <template slot-scope="scope">
          <el-button
            slot="reference" class="el-icon-delete opration_icon_btn"
            :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
            style="border: none;width: auto;height: auto"
            @click="deleteRow(scope)"></el-button>
        </template>
      </el-table-column>
    </el-table>
     <hr style="margin: 20px 0">
     <el-button style="margin-bottom: 10px;float: right;" size="mini" type="info" :loading="crud.rejectLoading"
                     @click="addBankData()" :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
          >
            添加银行
          </el-button>

      <el-table ref="bank-table" stripe border v-loading="crud.loading" :row-class-name="crud.tableRowClassName"
                :row-key="getRowKey"
                :data="crud.order.bankList" size="small" style="width: 100%;" :show-summary="true" sortable="custom"
      >
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('bankId')" prop="bankId"
                         label="银行"

        >
          <template slot-scope="{row,$index}">
            <zSelect :ref="'zSelect'+new Date().getTime()" :value.sync="row.bankId" :showName="row.bankName"
                     :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"
                     url="api/dropDown/basBankList"
                     style="width:  100%;"
                     :params="{sort: 'seq desc'}"
                     data-total-key="data.length"  @change="bankSelectFunc"
                     @focus="bankSelectFocus(row,$index)"
            />
          </template>
        </el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('bankOpenBranch')"
                         prop="bankOpenBranch" label="银行支行"
                         width="200"
        ></el-table-column>
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('bankAccount')" prop="bankAccount"
                         label="银行账户"
        />
        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')" prop="taxAmount"
                         label="金额"
        >
          <template slot-scope="{row}">
            <el-input v-model="row.taxAmount" @change="e=>bankTaxAmountChange(row)" :disabled="crud.order.orderStatus==='PASS' || crud.order.orderStatus==='CLOSE'"></el-input>
            <!-- :disabled="pageDisabled" -->
          </template>
        </el-table-column>

        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark" label="备注"/>
        <!-- <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('balanceAmount')" prop="balanceAmount"
                         label="账户余额"
        /> -->
        <el-table-column :render-header="crud.renderHeader" label="操作" fixed="right" width="150px" align="center"
                         v-if="!pageDisabled">
          <template slot-scope="scope">
            <el-button slot="reference" class="el-icon-delete opration_icon_btn"
                       :disabled="crud.order.orderStatus==='PASS'" style="border: none;width: auto;height: auto"
                       @click="bankDelAddRow(scope.$index)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

    <el-dialog
      title="请选择打印模板"
      :visible.sync="crud.printConfig.pringDialog"
      width="30%"
    >
      <jPrintConfig groupId="financeDailyCost"
                    v-if="crud.printConfig.pringDialog"
                    @getPrintId="crud.detailedPrint"
                    :isPreview="crud.printConfig.isPreview"
      ></jPrintConfig>
    </el-dialog>
  </div>
</template>

<script>
import crudFinanceDailyCost from '@/api/erp/financeDailyCost'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import Treeselect from "@riophae/vue-treeselect"
import {getDepts} from "@/api/system/dept";
import {getTree} from "@/api/erp/basSubject";
import ElSelectTree from 'el-select-tree'
import {Notification} from "element-ui";
import {getBusTime, isEmpty} from "@/utils";
import jPrintConfig from '@/components/jPrintConfig/jPrintConfig'
// crud交由presenter持有
const defaultCrud = CRUD({
  title: '日常费用',
  url: 'api/financeDailyCost/detail',
  sort: 'id,desc',
  optShow: {
    add: false,
    edit: false,
    del: false,
    download: false,
    downloadDetail: false,
    leadingIn: false,
    enable: false,
    disable: false,
    pass: false,
    reject: false,
    print: true,
    printDetail: true
  },
  params() {
    const href = location.href.split('/')
    if (href[5].includes('copyId')) {
      return {
        id: href[5].replace("copyId=",""),
      }
    } else {
      return {
        id: href[href.length - 1] == 'add' ? 0 : href[href.length - 1], page: 0, size: 999,
      }
    }
  },
  order: {
    taxAmount: 0.00,
    busDate: getBusTime(),
    detailList: [],
    bankList:[]
  },
  crudMethod: {...crudFinanceDailyCost}
})
const defaultForm = {
  id: null,
  code: null,
  name: null,
  type: null,
  busDate: null,
  supplierId: null,
  supplierCode: null,
  supplierName: null,
  customerId: null,
  customerCode: null,
  customerName: null,
  deptId: null,
  deptCode: null,
  deptName: null,
  userId: null,
  userCode: null,
  userName: null,
  bankId: null,
  bankCode: null,
  bankName: null,
  bankAccount: null,
  bankOpenName: null,
  bankOpenBranch: null,
  taxAmount: null,
  isPrint: null,
  printCount: null,
  seq: null,
  orderStatus: null,
  remark: null,
  orderRemark: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  auditUserId: null,
  auditUserCode: null,
  auditUserName: null,
  auditTime: null,
  closeUserId: null,
  closeUserCode: null,
  closeUserName: null,
  closeTime: null
}
export default {
  name: 'FinanceDailyCost',
  components: {pagination, crudOperation, rrOperation, udOperation, Treeselect, ElSelectTree, jPrintConfig},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['t_finance_bank_in_out_use_type', 'common_yes_or_no', 't_finance_daily_cost_type', 'common_order_status'],
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      permission: {
        add: ['admin', 'financeDailyCost:add'],
        edit: ['admin', 'financeDailyCost:edit'],
        del: ['admin', 'financeDailyCost:del'],
        import: ['admin', 'financeDailyCost:import'],
        export: ['admin', 'financeDailyCost:export'],
        copy: ['admin', 'financeDailyCost:copy'],
        upload: ['admin', 'financeDailyCost:upload'],
        download: ['admin', 'financeDailyCost:download'],
        pass: ['admin', 'financeDailyCost:pass'],
        reject: ['admin', 'financeDailyCost:reject'],
        closed: ['admin', 'financeDailyCost:closed'],
        invalid: ['admin', 'financeDailyCost:invalid'],
        stop: ['admin', 'financeDailyCost:stop'],
        recover: ['admin', 'financeDailyCost:recover'],
      },
      subjects: [],
      depts: [],
      bankList: [],
      userParams: {deptId: null},
      feeData: [{
        busDate: null,
        subjectCode: '',
        subjectName: '',
        goodsBrandName: '',
        taxAmount: 0.00,
        remark: '',
        orderRemark: ''
      }],
      selectSum: {
        sumTxtAmount: 0.00
      },
      editable: false,
      bankAccount: null,
      bankOpenBranch: null,
      selectRows: [],
      rules: {
        deptId: [
          {required: true, message: '部门不能为空', trigger: 'blur'}
        ],
        userId: [
          {required: true, message: '经办人不能为空', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '费用类型不能为空', trigger: 'blur'}
        ],
        bankId: [
          {required: true, message: '银行不能为空', trigger: 'blur'}
        ],
      }
    }
  },
  destroyed() {
    this.crud.setItemInfo("financeDailyCostDetail_add")
  },
  computed:{
    getTaxAmount(){
      return this.crud.order.taxAmount.toFixed(2)
    }
  },
  created() {
    this.adjustWidth()
    window.addEventListener('resize', this.adjustWidth.bind(this))
    this.getDepts()
    this.getSubjects()
    if (this.$route.params.id == 'add') {
      if (this.crud.getItemInfo("financeDailyCostDetail_add")) {
        return false
      }
      this.crud.order = {
        taxAmount: 0.00,
        busDate: getBusTime(),
        detailList: [],
        bankList: []

      }
    }
    console.log('33333333333',this.form);
    console.log('1111111111',this.crud.order);
  },
  watch: {},
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    [CRUD.HOOK.afterRefresh](crud, form) {
      const href = location.href.split('/')
      if(href[5].includes('copyId')){
        this.crud.order.orderStatus = 'SAVE'
      }
    },
    addBankData() {
        if(!this.crud.order.bankList)
        this.$set(this.crud.order,'bankList',[])
      let bankItem = {
        bankKeyFlag: 'bankKeyFlag-' + new Date().getTime(),
        bankId: '',
        bankName: '',
        bankOpenBranch: '',
        bankAccount: '',
        balanceAmount: '',
        taxAmount: '',
        remark: '',
        cancelAmount: 0,
        unCancelAmount: 0
      };
      this.crud.order.bankList.push(bankItem)
    },
    // 选择银行之后
    bankSelectFunc(selectedBank) {
      const {id, name, bankOpenBranch, bankAccount, balanceAmount, remark} = selectedBank;
      const idx = this.bankFocusedIdx;
      if (idx >= 0) {
        const {taxAmount, bankKeyFlag} = JSON.parse(JSON.stringify(this.crud.order.bankList[idx]));
        this.crud.order.bankList.splice(idx, 1, {
          bankKeyFlag,
          bankId:id,
          bankName:name,
          bankOpenBranch,
          bankAccount,
          balanceAmount,
          taxAmount,
          remark,
          cancelAmount: 0,
          unCancelAmount: 0,
        });
      }
    },
    // 银行数据中当前选中的某行
    bankSelectFocus(row, idx) {
      this.bankFocusedIdx = idx;
    },
    // 删除银行
    bankDelAddRow(i) {
      this.crud.order.bankList.splice(i, 1);
      // 重新计算尾差和本次核销金额
      this.curCancelAmountChange();
      this.residueAmountChange();
      this.bankTaxAmountChange();
      this.$forceUpdate();
    },
    changeSubjects(e, index) {
      this.crud.order.detailList[index].subjectCode = e.code
      this.crud.order.detailList[index].subjectName = e.name
    },
    getValue(e) {
      this.query.startTime = this.query.dataExtent[0]
      this.query.endTime = this.query.dataExtent[1]
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    getDepts() {
      getDepts({status: 1}).then(res => {
        this.depts = res
      })
    },
    changeBank(data) {
      this.crud.order.bankAccount = data.bankAccount
      this.crud.order.bankOpenBranch = data.bankOpenBranch
      this.crud.order.bankCode = data.code
      this.crud.order.bankName = data.name
      this.crud.order.bankOpenName = data.bankOpenName
    },
    deleteRow(scope) {
      if (this.crud.order.detailList.length === 1) {
        this.$message.error("表格至少要有一行，不能删除")
      } else {
        this.crud.order.detailList.splice(scope.$index, 1)
      }
      this.changeMoney()
    },
    addRow(scope) {
      let bankItem = {
        busDate: null,
        subjectCode: null,
        subjectName: '',
        goodsBrandName: '',
        taxAmount: 0.00,
        remark: '',
        orderRemark: ''
      }
      if (scope !== 0) {
        this.crud.order.detailList.splice(scope.$index + 1, 0, bankItem)
      } else {
        this.crud.order.detailList.push(bankItem)
      }
    },
    sumMoney({columns, data}) {
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (column.property === 'taxAmount') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0).toFixed(2);
          sums[index];

        }
      });
      return sums
    },
    changeMoney() {
      console.log('111111',this.crud.order.detailList);
      this.crud.order.taxAmount = 0.00
      for (let i = 0; i < this.crud.order.detailList.length; i++) {
        this.crud.order.taxAmount += this.crud.order.detailList[i].taxAmount
      }
    },
    adjustWidth() {
      this.$nextTick(() => {
        if (this.$refs && this.$refs.sum_xiaoji && this.$refs.feeTable && this.$refs.feeTable.$refs.headerWrapper) {
          var width = getComputedStyle(this.$refs.feeTable.$refs.headerWrapper.querySelector('table')).width
          this.$refs.sum_xiaoji.style = 'width:' + width
          Array.from(this.$refs.feeTable.$refs.headerWrapper.querySelectorAll('col')).forEach((n, i) => {
            if (this.$refs.sum_xiaoji.children[i]) {
              this.$refs.sum_xiaoji.children[i].style = 'width:' + n.getAttribute('width') + 'px'
            }
          })
        }
      })
    },
    selectChange(val) {
      this.selectRows = val
      this.getSelectSum()
    },
    getSelectSum() {
      var amount = 0.00
      this.selectRows.forEach((n, i) => {
        amount += Number.parseFloat(n.taxAmount)
      })
      this.selectSum.sumTxtAmount = amount.toFixed(2)
    },

    // 保存提交
    submit() {
       console.log('12',this.crud.order);
      this.$refs['orderForm'].validate(valid => {
        if (!valid) {
          return
        }
        const order_rules = [
          {name: '请输入编号', value: 'subjectCode'},
          {name: '请输入费用名称', value: 'subjectId'},
          {name: '请输入金额', value: 'taxAmount'}
        ]
        let detailList = this.crud.order.detailList
        if (!this.tableRules(detailList, order_rules, "您还没有新增费用")) {
          return;
        }
        this.crud.order.bankOpenName=(this.crud.order.bankList.map((item)=>{
          return item.bankName
        })).toString()
        // for (let i = 0; i < this.crud.order.bankList.length; i++) {
        //  this.crud.order.bankName.push(this.crud.order.bankList[i].bankName)

        // }
        this.save()
      })
    },

    //保存
    save() {
      let that = this
      that.crud.loadingOpen()
      const href = location.href.split('/')
      if (href[5].includes('copyId')) {
        this.crud.order.id = 0
        for (let i = 0; i < this.crud.order.detailList.length; i++) {
          this.crud.order.detailList[i].id = null
          this.crud.order.detailList[i].orderId = null
        }
      }
      crudFinanceDailyCost.add(this.crud.order).then(res => {
        if (res.status === 200) {
          this.crud.order = res.data.order
          let id = res.data.order.id
          if (this.$route.params.id == 'add' || href[5].includes('copyId')) {
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({params: {id}})
            this.crud.cleanItemInfo("financeDailyCostDetail_add")
          }
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          that.crud.loadingClose()
          this.crud.refresh()
        } else {
          that.crud.loadingClose()
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        }

      }).catch((res) => {
        that.crud.loadingClose()
      })
    },
    tableRules(list, rules, nullMsg) {
      let flag = true
      if (list === null || list.length === 0) {
        Notification.error({title: nullMsg})
        return false
      }
      rules.forEach(rule => {
        for (let i = 0; i < list.length; i++) {
          if (!list[i][rule.value]) {
            Notification.error({title: '序号【' + (i+1) + '】' + rule.name + '不能为空'})
            flag = false
            break
          }
        }
      })
      return flag
    },
    changeDept(e) {
      const {id} = e
      this.userParams.deptId = id
    },
    getSubjects() {
      getTree().then(res => {
        this.subjects = []
        const subjects = {id: 0, name: '顶级分类', children: []}
        subjects.children = res.data
        this.subjects.push(subjects)
      })
    },
    changeSupplier(e) {
      this.crud.order.supplierId = e.id
      this.crud.order.supplierName = e.name
    },
    changeCustomer(e) {
      this.crud.order.customerId = e.id
      this.crud.order.customerName = e.name
    },
    copyOrder() {
      if(isEmpty(this.crud.order.id) || this.crud.order.id === 0){
        this.$message.error("请保存后再复制")
        return
      }
      this.crud.toCopy(this.crud.order.id,"/finance/financeDailyCostDetail")
    }
  }
}
</script>

<style scoped>
.sum_footer {
  display: flex;
  display: -webkit-flex;
  line-height: 50px;
  color: #606266;
}

.sum_footer_unit {
  flex-grow: 1;
  -webkit-flex-grow: 1;
  text-indent: 10px;
}

.sum_footer_unit.center {
  text-align: center;
}

.sum_footer.xiaoji {
  border-bottom: 1px solid #EBEEF5;
}
/* .handler-div {
  padding-top: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
} */
</style>
